
package com.gzbsoft.sc.modules.sys.controller;
import com.gzbsoft.sc.common.utils.R;
import com.gzbsoft.sc.common.utils.SmsVerification;
import com.gzbsoft.sc.common.validator.ValidatorUtils;
import com.gzbsoft.sc.modules.app.form.RegisterForm;
import com.gzbsoft.sc.modules.sys.entity.SysUser;
import com.gzbsoft.sc.modules.sys.form.SysLoginForm;
import com.gzbsoft.sc.modules.sys.service.SysUserService;
import com.gzbsoft.sc.modules.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
@Api("登录相关")
@RestController
public class SysLoginController extends AbstractController {
    private final SysUserService sysUserService;
    private final SysUserTokenService sysUserTokenService;
    public SysLoginController(SysUserTokenService sysUserTokenService ,SysUserService sysUserService ) {
        this.sysUserService = sysUserService;
        this.sysUserTokenService = sysUserTokenService;
    }
    @ApiOperation("获取验证码")
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
    }
    @ApiOperation("登录得到Token")
    @PostMapping("/sys/login")
    public R login(@RequestBody SysLoginForm form) {
        /**
         * 登录判断逻辑：如果注册的是买家，登录时选择卖家 可以进入卖家后台
         * 通过type类型判断 用户类型: 1: 个人用户, 2: 商家, 3: 商家子账号
         */
        //用户信息
        SysUser user = sysUserService.queryByUserName(form.getUsername()).orElse(null);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error(201,"用户名或密码不正确");
        }
        //账号锁定
        if (user.isDelFlag()) {
            return R.error(202,"账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库
        return sysUserTokenService.createToken(user.getId());

    }
    @ApiOperation("退出")
    @PostMapping("/sys/logout")
    public R logout() {//HttpSession session
        //session.removeAttribute("token");
        return R.ok();
    }

    @ApiOperation("注册")
    @PostMapping("/sys/register")
    public R register(@RequestBody RegisterForm form , HttpSession session){
        Date date = new Date();
        long nowTime = date.getTime();
        Object time = session.getAttribute("registerOutTime");
        if(time == null || time.equals(null)){
            return R.error("验证码已过期");
        }else{
            long  dateTime = (long)session.getAttribute("registerOutTime")+(long)60000;
            if(nowTime>dateTime){
                session.removeAttribute("registerOutTime");
                return R.error("验证码已过期");
            }
            Object registerCode =session.getAttribute("registerCode");
            if(!StringUtils.isEmpty(registerCode) && !registerCode.equals(form.getSecurityCode())){
                return R.error("验证码错误");
            }
        }
            ValidatorUtils.validateEntity(form);
            sysUserService.register(form);
            //根据手机号查询用户信息
            return R.ok("注册成功");
    }

    @ApiOperation("校验手机号是否注册")
    @GetMapping("/isRegisterByTel")
    public R isRegisterByTel(@RequestParam String mobile){
        if(mobile == null || mobile == ""){
            return R.error("手机号不能为空");
        }
        return sysUserService.isRegisterByTel(mobile);
    }
    @ApiOperation("发送验证码")
    @GetMapping("/sendRegister")
    public R sendRegister(@RequestParam String tel,HttpSession session) throws  Exception{
        Date date = new Date();
        String registerCode = SmsVerification.UUSix();
        SmsVerification.sendSms(tel,registerCode);
        session.setAttribute("registerOutTime",date.getTime());
        session.setAttribute("registerCode",registerCode);
        return R.ok();
    }
}
